package Actions;

import java.sql.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.StudentModel;

import org.apache.struts.action.*;

public class startRevAction extends Action
{
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response){
		
		//forms.ChairsHomeForm ch = (forms.ChairsHomeForm) form;
		
		String url = "jdbc:postgresql://localhost:5432/Applications";
		Connection conn = null;
		PreparedStatement ps = null;
		Statement stmt = null;
		Statement stmt2 = null;
		ResultSet rs = null;
		ResultSet rs2 = null;
		int numRev = 0, count = 1, i = 1;
		
		try {
			// Registering Postgresql JDBC driver
			Class.forName("org.postgresql.Driver");
			// Open a connection to the database	
			conn = DriverManager.getConnection(url,"postgres","postgres");
			stmt = conn.createStatement();
			stmt2 = conn.createStatement();

		    ps = conn.prepareStatement("INSERT INTO revProc(started) VALUES(?)");
		    ps.setInt(1,1);
		    ps.executeUpdate();
		    
		    numRev = StudentModel.numReviewers();
		    
		    rs = stmt.executeQuery("SELECT * FROM Application");
	        
	        //assign each application to each of the 3 reviewers in a round-robin way
	        while( rs.next() )
	        {
	        	if( count > numRev )
	        	{
	        		count = 1;
	        	}
	        	ps = conn.prepareStatement("UPDATE Application SET rev_id = " + count + " WHERE " +
	        			"app_id = " + i );
	        	ps.executeUpdate();

			    rs2 = stmt2.executeQuery("SELECT appNotGra FROM Reviewers WHERE rev_id = '"+count+"'");
	        	
			    rs2.next();
			    int countGraded = rs2.getInt("appNotGra") + 1;
			    System.out.println("count"+countGraded);
	        	ps = conn.prepareStatement("UPDATE Reviewers SET appNotGra = " + countGraded + " WHERE " +
	        			"rev_id = " + count );
	        	ps.executeUpdate();
	        	
	        	count++;	
	        	i++;
	        }
		    
		    
			// close connection
	        rs.close();
	        if (rs2 != null) 
	        rs2.close();
	        stmt.close();
	        stmt2.close();
			ps.close();
			conn.close();
			
		} catch (SQLException e) 
		{ 
			System.out.println(e);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	
		return mapping.findForward("startRevSuccess");
	}
}
